package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.heima.model.common.constants.wemedia.WemediaConstants.WM_NEWS_DOWN;
import static com.heima.model.common.constants.wemedia.WemediaConstants.WM_NEWS_UP;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 条件查询所有自媒体文章
     *
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        // 1.参数校验
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        // 1.1 如果有文章状态,根据文章状态查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 1.2 如果有关键字,就根据关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        // 1.3 根据频道列表查询文章
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        // 1.4 根据文章发布日期区间查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> result = this.page(page, wrapper);
        // 2.返回数据给前端
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal(), result.getRecords());
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1.参数校验()
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.2 将dto对象复制给对应的WmNews实体类对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //如果文章布局是自动，需要设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //处理dto参数 images封面集合 转换成 字符串
        if (CollectionUtils.isNotEmpty(dto.getImages())) {
            String image = imageListToStr(dto.getImages(), webSite);
            // 2.发布或修改文章
            wmNews.setImages(image);
        }
        saveWmNews(wmNews);

        //  3.1 抽取文章中关联的图片路径
        List<Map> contents = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = parseContentImages(contents);
        //  3.2 关联文章内容中的图片和素材关系
        Short status = dto.getStatus();
        if (CollectionUtils.isNotEmpty(materials)) {
            saveRelativeInfo(materials, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //  3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(dto, materials, wmNews);

        // 3.4 发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("文章已经成功发送,文章ID ->{}", wmNews.getId());

        return ResponseResult.okResult();
    }

    /**
     * 查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 1.参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
//        if (wmUser == null) {
//            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
//        }
        WmNews wmNews = this.getById(id);
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }


    /**
     * 删除文章
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus()) &&
                WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文章已发布,不能删除");
        }

        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));

        //5.删除文章
        removeById(id);
        return ResponseResult.okResult();

//        //1.检查参数
//        if(id == null){
//            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
//        }
//        //2.获取数据
//        WmNews wmNews = getById(id);
//        if(wmNews == null){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
//        }
//        //3.判断当前文章的状态  status==9  enable == 1
//        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
//                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
//        }
//        //4.去除素材与文章的关系
//        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
//        //5.删除文章
//        removeById(wmNews.getId());
//        return ResponseResult.okResult();

    }

    /**
     * 上下架
     *
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {

        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));
        if (wmNews.getArticleId() != null){
            // 上架消息
            if (enable.equals(WM_NEWS_UP)){
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        // 1.参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //
        Integer page = dto.getPage();
        dto.setPage((page - 1) * dto.getSize());
        long total = wmNewsMapper.findListCount(dto);
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);

        PageResponseResult result = new PageResponseResult(page, dto.getSize(), total, wmNewsVOList);
        result.setHost(webSite);
        return result;

    }

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        // 参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章ID不能为空");
        }
        // 查询文章信息
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 查询作者信息
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }

        // 将wmNews分装成vo对象
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        wmNewsVO.setAuthorName(wmUser.getName());
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 修改文章
     *
     * @param status
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        // 参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //如果文章ID不为空,根据ID查找文章
        WmNews wmNews = null;
        if (dto.getId() != null) {
            wmNews = wmNewsMapper.selectById(dto.getId());
        }
        // 如果文章的状态不为3,则不进行人工审核
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = System.currentTimeMillis();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materials, WmNews wmNews) {
        List<String> images = dto.getImages();

        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int materialSize = materials.size();
            // 单图
            if (materialSize > 0 && materialSize <= 2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                // 多图
            } else if (materialSize > 2) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                // 无图
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                String image = imageListToStr(images, webSite);
                wmNews.setImages(image);
            }
            updateById(wmNews);
        }
        if (images != null && images.size() > 0) {
            images = images.stream()
                    .map(x -> x.replaceAll(webSite, ""))
                    .collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
        //1 查询文章内容中的图片对应的素材ID
        List<Integer> materialIds = wmMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());
        //2 判断素材是否缺失
        if (materialIds.size() < urls.size() || CollectionUtils.isEmpty(materialIds)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失,保存文章失败");
        }
        //3 保存素材关系
        wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);


    }

    private List<String> parseContentImages(List<Map> contents) {
        return contents.stream()
                // 过滤type=image所有的集合
                .filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                // 获取到image下的value  图片url
                .map(x -> x.get("value").toString())
                // 图片url去除前缀
                .map(url -> url.replaceAll(webSite, ""))
                // 去除重复的路径
                .distinct()
                // sretam 转成list集合
                .collect(Collectors.toList());

    }

    private void saveWmNews(WmNews wmNews) {
        wmNews.setSubmitedTime(new Date());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        // 如果文章id为空,就保存文章
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else { // 不为空就修改文章
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }
    }

    private String imageListToStr(List<String> images, String webSite) {
        return images.stream()
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));

    }
}
